//
//  HeadlineView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/30.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol HeadlineViewDelegate {
    @objc optional func scrollToFrame(y:CGFloat) //滑动到指定位置
    @objc optional func selectItem(index:Int) //选择标签
    @objc optional func selectNews(model:NewsModel) //选择新闻
    @objc optional func updateHeadlineTiltle() //更新标题
}

class HeadlineView: UIView {
    
    weak var delegate : HeadlineViewDelegate?
    
    var titleArray = [String]() {
        didSet{
            headView.dataArray = titleArray
        }
    }
    
    var urlString : String! {
        didSet{
            self.getData(url: urlString)
        }
    }
    

    fileprivate let cellId = "headLineCell"
    fileprivate var dataArray = [NewsModel]()
    fileprivate var tableView : UITableView!
    
    let headView = TitleHeadView()
    
    fileprivate var page = 1 //页数

    init() {
        super.init(frame: .zero)
        
        headView.delegate = self
        self.addSubview(headView)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.register(NewsCell.self, forCellReuseIdentifier: cellId)
        self.addSubview(tableView)
        
        headView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData(url: (self?.urlString)!)
            
        }) {[weak self] in
            
            self?.getData(url: (self?.urlString)! + "/p\(self!.page)")
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 获取数据
    fileprivate func getData(url:String) {
        
        if self.dataArray.count == 0 {
            //读取资讯缓存数据
            switch self.urlString {
            case url_informationNews://资讯新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: informationNewsTitle) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: informationNewsData) as! [NewsModel]
                    self.tableView.reloadData()
                }
            case url_financialNews://理财新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: financialNewsData) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: financialNewsData) as! [NewsModel]
                    self.tableView.reloadData()
                }
            case url_loanNews://贷款新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: loanNewsData) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: loanNewsData) as! [NewsModel]
                    self.tableView.reloadData()
                }
            default:
                break
            }
        }
        
        self.delegate?.updateHeadlineTiltle!()
        
        KMTool.requestGetData(URLString: url, parameters: nil, success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            let elements = ["//div[@id='content']/section/li/a","//div[@id='content']/section/li/a/img","//div[@id='content']/section/li/a/div[@class='content']/span[@class='span_top']","//div[@id='content']/section/li/a/div[@class='content']/small"]
            let attributes = ["href","src","text","text"]
            let keys = ["href","image","title","time"]
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count == 0 {
                return
            }else{
                if self.page == 1 {
                    self.dataArray.removeAll()
                }
                self.page += 1
            }
            
            for item in array {
                let model = NewsModel.setModel(with: item)
                self.dataArray.append(model)
            }
            
            if self.page == 2 {
                //缓存资讯内容
                switch self.urlString {
                case url_informationNews://资讯新闻
                    NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: informationNewsData)
                case url_financialNews://理财新闻
                    NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: financialNewsData)
                case url_loanNews://贷款新闻
                    NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: loanNewsData)
                default:
                    break
                }
            }
            
            
            self.tableView.reloadData()
            
        }) {
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }
}

extension HeadlineView : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 100)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? NewsCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        self.delegate?.selectNews!(model: dataArray[indexPath.row])
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.delegate?.scrollToFrame!(y: scrollView.contentOffset.y)
    }
}

extension HeadlineView : TitleHeadViewDelegate {
    
    //MARK: 选择标签
    func selectItem(index: Int) {
        
        self.delegate?.selectItem!(index: index)
    }
    
    
    
}
